﻿using System;
using System.IO;
using System.Threading;
using agsXMPP;
using agsXMPP.protocol.client;
using agsXMPP.Xml.Dom;
using EAGetMail;
using MailChatSms;

namespace Experiments
{
    partial class Program
    {
        static Xmpp gtalk;
        static void messageReceived(string msgText)
        {
            Console.WriteLine("Message received: " + msgText);
        }

        static void PlayWithGtalk()
        {
            gtalk = new Xmpp("@gmail.com", "!", messageReceived);

            if (gtalk.Start())
            {
                Console.WriteLine("Started Gtalk client...");
                if (gtalk.Send("@gmail.com", "How are you"))
                {
                    Console.WriteLine("Send Success");
                }
            }
        }

        static void messageReceived(object sender, agsXMPP.protocol.client.Message msg)
        {
            if (!string.IsNullOrEmpty(msg.Body))
            {
                string[] chatMessage = msg.From.ToString().Split('/');

                //_handler(msg.Body);

                Jid jid = new Jid(chatMessage[0]);
                Message autoReply = new Message(jid, MessageType.chat, "Received: " + msg.Body);
                _objXmpp.Send(autoReply);
            }
        }

        private static void loginFailed(object o, agsXMPP.Xml.Dom.Element el)
        {
            Console.WriteLine("Login failed. Please check your details.");
        }

        private static void loggedIn(object o)
        {
            Console.WriteLine("Logged in and Active.");
        }
        private static void OnError(object o, Exception ex)
        {
            _objXmpp.Close();
            Start();
        }
        private static void OnStreamError(object o, Element e)
        {
            _objXmpp.Close();
            Start();
        }
        public static bool Send(string to, string msgText)
        {
            bool success = false;
            try
            {
                Message msg = new Message(to, MessageType.chat, msgText);
                _objXmpp.Send(msg);
                success = true;
            }
            catch (Exception ex)
            {
                //Logger.LogException(ex);
            }

            return success;
        }

        static XmppClientConnection _objXmpp;
        public static bool Start()
        {
            bool success = false;
           
            try
            {
                _objXmpp.Open();
                success = true;
            }
            catch (Exception ex)
            {
                //Logger.LogException(ex);
            }

            return success;
        }

        static void PlayWithGtalk1()
        {
            _objXmpp = new XmppClientConnection();
            Jid jid = new Jid("mypop213@gmail.com");
            _objXmpp.Password = "!";
            _objXmpp.Username = jid.User;
            _objXmpp.Server = jid.Server;
            _objXmpp.AutoResolveConnectServer = true;

            _objXmpp.OnMessage += messageReceived;
            _objXmpp.OnLogin += loggedIn;
            _objXmpp.OnAuthError += loginFailed;
            _objXmpp.OnError += OnError;
            _objXmpp.OnRegisterError += OnStreamError;
            _objXmpp.OnStreamError += OnStreamError;
            _objXmpp.OnSocketError += OnError;

            Start();

        }

        static Imap gmail;
        static void PlayWithMail()
        {
            Smtp emailer = new Smtp("smtp.gmail.com", 587, "@gmail.com", "!", true);
            short code = 0;

            //if (code == 0)
            //{
            //    //PopMail.POP3MailProcessor reader = new POP3MailProcessor("pop.gmail.com", 995, "mypop213@gmail.com", "!");

            //    //reader.ProcessMails(MailProcessor);
            //}
            gmail = new Imap("mypop213@gmail.com", "!", messageReceived);
            //ReadEmails();
            while (true)
            {
                gmail.ReadEmails();
                int i = new Random().Next();
                code = emailer.SendMail("tester@gmail.com", "mypop213@gmail.com", "test-s", "test-b:" + i, false, 3);
                Thread.Sleep(1000 * 5);
            }

            gmail.Close();
            emailer.Dispose();
        }




        static void ReadEmails()
        {
            // Create a folder named "inbox" under current directory
            // to save the email retrieved.
            string curpath = Directory.GetCurrentDirectory();
            string mailbox = String.Format("{0}\\inbox", curpath);

            // If the folder is not existed, create it.
            if (!Directory.Exists(mailbox))
            {
                Directory.CreateDirectory(mailbox);
            }

            MailServer oServer = new MailServer("imap.gmail.com",
                        "mypop213@gmail.com", "!", ServerProtocol.Imap4);
            MailClient oClient = new MailClient("TryIt");

            // Set IMAP4 server port
            //oServer.Port = 143;

            // If your IMAP server requires SSL connection,
            // Please add the following codes:
            oServer.SSLConnection = true;
            oServer.Port = 993;

            try
            {
                oClient.Connect(oServer);
                MailInfo[] infos = oClient.GetMailInfos();
                for (int i = 0; i < infos.Length; i++)
                {
                    MailInfo info = infos[i];
                    Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
                        info.Index, info.Size, info.UIDL);

                    // Receive email from IMAP4 server
                    Mail oMail = oClient.GetMail(info);

                    Console.WriteLine("From: {0}", oMail.From.ToString());
                    Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

                    // Generate an email file name based on date time.
                    System.DateTime d = System.DateTime.Now;
                    System.Globalization.CultureInfo cur = new
                        System.Globalization.CultureInfo("en-US");
                    string sdate = d.ToString("yyyyMMddHHmmss", cur);
                    string fileName = String.Format("{0}\\{1}{2}{3}.eml",
                        mailbox, sdate, d.Millisecond.ToString("d3"), i);

                    // Save email to local disk
                    oMail.SaveAs(fileName, true);

                    // Mark email as deleted from IMAP4 server.
                    //oClient.Delete(info);
                }

                // Quit and purge emails marked as deleted from IMAP4 server.
                oClient.Quit();
            }
            catch (Exception ep)
            {
                Console.WriteLine(ep.Message);
            }
        }

    }
}
